using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class MouseManager : MonoBehaviour
{
    //点,门口,攻击,目标,箭头对应鼠标图片
    public Texture2D point, doorway, attack, target, arrow;
    private NavMeshAgent agent;
    private Animator animator;
    RaycastHit hitInfo;
    //攻击cd
    private float lastAttackTime;
    //敌人
    private GameObject attackTarget;

    void Awake()
    {
        //获取代理组件
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();

    }

    private void Start()
    {

    }

    private void Update()
    {
        MouseController();
        SwitchAnimation();

        lastAttackTime -= Time.deltaTime;
    }

    void MouseController()
    {
        //获取鼠标位置
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //如果按下鼠标
        if (Input.GetMouseButtonDown(0))
        {
            agent.isStopped = false;//还原开始
            //判断射线是否碰到物体
            if (Physics.Raycast(ray, out hitInfo))
            {
                //点击的位置
                Vector3 point = hitInfo.point;
                //设置该位置为导航目标点
                agent.SetDestination(point);
                if (hitInfo.collider.gameObject.tag == "Enemy")
                {
                    attackTarget = hitInfo.collider.gameObject;
                    StartCoroutine(MoveToAttackTarget());
                }else{
                    //终止所有携程
                    StopAllCoroutines();
                }
            }
        }
        if (Physics.Raycast(ray, out hitInfo))
        {

            //切换鼠标图片
            switch (hitInfo.collider.gameObject.tag)
            {
                case "Ground":
                    Cursor.SetCursor(target, new Vector2(16, 16), CursorMode.Auto);
                    break;
                case "Enemy":
                    Cursor.SetCursor(attack, new Vector2(16, 16), CursorMode.Auto);
                    break;
            }
        }
    }

    //动画的切换
    void SwitchAnimation()
    {
        animator.SetFloat("Speed", agent.velocity.sqrMagnitude);
    }

    //携程
    IEnumerator MoveToAttackTarget()
    {
        agent.isStopped = false;

        //如果和敌人的距离大于1.5
        //TODO: 距离可修改
        while (Vector3.Distance(attackTarget.transform.position, transform.position) > 1.5)
        {
            yield return null;
        }
        transform.LookAt(attackTarget.transform);//转向敌人
        agent.isStopped = true;//停止
        if (lastAttackTime <= 0)
        {
            //播放攻击动画
            animator.SetTrigger("Attack");
            //重置冷却时间
            lastAttackTime = 0.5f;
        }
    }
}
